package com.hualan.listener;

//请求对象的监听器，用来完成请求对象的创建和销毁过程的监听。
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.util.DruidDataSourceUtils;
import com.alibaba.druid.util.DruidWebUtils;


import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

@WebListener
public class RequestListener implements ServletRequestListener {
    private Connection conn;
    //定义一个数据库连接池对象
    private static DataSource dataSource;

    static {
        //加载Druid对应的属性配置文件，将配置文件中的内容转换成输入流
        try {
            System.out.println("开始数据库链接");
            InputStream resourceStream = DruidWebUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            Properties properties = new Properties();
            //将文件中的配置内容转换成properties对象
            properties.load(resourceStream);
            System.out.println(properties);
            //根据properties对象创建数据库连接池对象
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        HttpServletRequest req = (HttpServletRequest) sre.getServletRequest();
        if(!req.getServletPath().endsWith("html") && !req.getServletPath().endsWith("htm")){
            //获取数据库链接对象同时创建sql执行对象
            try {
                this.conn = dataSource.getConnection();
                //关闭connection自动提交功能
                conn.setAutoCommit(false);
                //将执行对象存入到请求对象中
                sre.getServletRequest().setAttribute("conn", this.conn);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        //请求被销毁
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
